#include "dlgleaseedit.h"
#include "ui_dlgleaseedit.h"
#include <QDebug>


DlgLeaseEdit::DlgLeaseEdit(QWidget *parent) :
    QDialog(parent),
    m_num_check(false),
    ui(new Ui::DlgLeaseEdit)
{
    ui->setupUi(this);

    mp_te = new FormTown(this);
    mp_te->hide();
    mp_te->setWindowFlags(Qt::Dialog);
    mp_te->setWindowModality(Qt::ApplicationModal);

    mp_pe = new FormPeople(this);
    mp_pe->hide();
    mp_pe->setWindowFlags(Qt::Dialog);
    mp_pe->setWindowModality(Qt::ApplicationModal);

    mp_de = new FormDecMasters(this);
    mp_de->hide();
    mp_de->setWindowFlags(Qt::Dialog);
    mp_de->setWindowModality(Qt::ApplicationModal);

    connect(ui->btn_ok, SIGNAL(clicked()), this, SLOT(accept()));
    connect(ui->btn_cancel, SIGNAL(clicked()), this, SLOT(reject()));

    connect(ui->btn_select_person, SIGNAL(clicked()), mp_pe, SLOT(show()));
    connect(ui->btn_select_apartment, SIGNAL(clicked()), mp_te, SLOT(show()));
    connect(ui->btn_dec_add, SIGNAL(clicked()), mp_de, SLOT(show()));
    connect(ui->btn_dec_del, SIGNAL(clicked()), this, SLOT(del_decmaster()));

    connect(mp_te, SIGNAL(record_selected(QVariant)), this, SLOT(select_apartment(QVariant)));
    connect(mp_pe, SIGNAL(record_selected(QVariant)), this, SLOT(select_tenant(QVariant)));
    connect(mp_de, SIGNAL(record_selected(QVariant)), this, SLOT(add_decmaster(QVariant)));
    connect(ui->dedit_dec, SIGNAL(dateChanged(QDate)), this, SLOT(dec_date_changed()));
    connect(ui->ledit_dec_num, SIGNAL(textEdited(QString)), this, SLOT(dec_num_changed()));

    connect(ui->listWidget_decisions, SIGNAL(itemSelectionChanged()), this, SLOT(dec_list_sel()));

    mpq_space_validator = new QDoubleValidator(this);
    mpq_num_validator = new QIntValidator(this);
    ui->ledit_ls_num->setValidator(mpq_num_validator);
    mp_te->enable_selection();
    mp_pe->enable_selection();
}

DlgLeaseEdit::~DlgLeaseEdit()
{
    delete ui;
}


void DlgLeaseEdit::set_dbms(HousingDBMS *p_dbms)
{
    mp_dbms = p_dbms;
    mp_te->set_dbms(mp_dbms);
    mp_pe->set_dbms(mp_dbms);
    mp_de->set_dbms(mp_dbms);
}

void DlgLeaseEdit::set_settings(DlgSettings *p_settings)
{
    mp_settings = p_settings;

    ui->combo_lfio->clear();
    ui->combo_lhead->clear();
    ui->combo_lhead->addItems(mp_settings->get_lender_heads());
    ui->combo_lfio->addItems(mp_settings->get_lender_heads_fio());
}

void DlgLeaseEdit::setup_connection()
{
    connect(ui->ledit_dec_num, SIGNAL(textChanged(QString)), this, SLOT(data_changed()));
    connect(ui->combo_lhead, SIGNAL(editTextChanged(QString)), this, SLOT(data_changed()));
    connect(ui->combo_lfio, SIGNAL(editTextChanged(QString)), this, SLOT(data_changed()));
    connect(ui->ledit_ls_num, SIGNAL(textChanged(QString)), this, SLOT(data_changed()));
    connect(ui->ledit_stopreason, SIGNAL(textChanged(QString)), this, SLOT(data_changed()));
    connect(ui->dedit_dec, SIGNAL(dateChanged(QDate)), this, SLOT(data_changed()));
    connect(ui->dedit_edate, SIGNAL(dateChanged(QDate)), this, SLOT(data_changed()));
    connect(ui->dedit_sdate, SIGNAL(dateChanged(QDate)), this, SLOT(data_changed()));
}

void DlgLeaseEdit::data_to_form()
{
    if(mqh_data.size() < 1)
    {
        ui->ledit_stopreason->hide();
        ui->dedit_edate->hide();
        ui->label_reason_date->hide();
        ui->label__reason->hide();
        ui->dedit_edate->setDate(QDate(2222,1,1));
        ui->ledit_stopreason->setText(RUSTR("Действующий."));
        return;
    }

    ui->ledit_ls_num->setText(mqh_data.value(FLD_LS_NUM).toString());

    ui->combo_lhead->addItem(mqh_data.value(FLD_LS_LENDER_HEAD).toString());
    ui->combo_lfio->addItem(mqh_data.value(FLD_LS_LENDER_HFIO).toString());
    ui->combo_lhead->setCurrentIndex(ui->combo_lhead->count()-1);
    ui->combo_lfio->setCurrentIndex(ui->combo_lfio->count()-1);

    ui->ledit_stopreason->setText(mqh_data.value(FLD_LS_REASON).toString());
    ui->tedit_comments->setPlainText(mqh_data.value(FLD_LS_COMM).toString());
    ui->dedit_edate->setDate(mqh_data.value(FLD_LS_EDATE).toDate());
    ui->dedit_sdate->setDate(mqh_data.value(FLD_LS_SDATE).toDate());
    select_apartment(mqh_data.value(FLD_LS_AINDEX));
    select_tenant(mqh_data.value(FLD_LS_TINDEX));

    if(!mqh_data.contains(FLD_LS_DECLST)) return;

    mqvl_dec_indices = mqh_data.value(FLD_LS_DECLST).toList();
    mqvl_dec_dates = mqh_data.value(FLD_LS_DDATESLST).toList();
    mqvl_dec_nums = mqh_data.value(FLD_LS_DNUMLST).toList();
    dec_list_to_form();
}

void DlgLeaseEdit::form_to_data()
{
   //TINDEX and AINDEX sets automaticaly

    mqh_data[FLD_LS_SDATE] = ui->dedit_sdate->date();
    mqh_data[FLD_LS_EDATE] = ui->dedit_edate->date();
    mqh_data[FLD_LS_NUM] = ui->ledit_ls_num->text().toInt();
    mqh_data[FLD_LS_COMM] = ui->tedit_comments->toPlainText();
    mqh_data[FLD_LS_LENDER_HEAD] = ui->combo_lhead->currentText();
    mqh_data[FLD_LS_LENDER_HFIO] = ui->combo_lfio->currentText();
    mqh_data[FLD_LS_REASON] = ui->ledit_stopreason->text();
    mqh_data[FLD_LS_DDATESLST] = mqvl_dec_dates;
    mqh_data[FLD_LS_DECLST] = mqvl_dec_indices;
    mqh_data[FLD_LS_DNUMLST] = mqvl_dec_nums;
    QStringList qsl_s_indices;
    for(int i = 0; i< ui->list_spaces->count(); i++)
    {
        QListWidgetItem *p_i = ui->list_spaces->item(i);
        if(p_i->checkState() == Qt::Checked)
        {
            qsl_s_indices.append(mqsl_ap_sps_ids.at(i));
        }
    }
    mqh_data[FLD_LS_SPSLST] = QVariant(qsl_s_indices);
}

void DlgLeaseEdit::showEvent(QShowEvent * ev)
{
    mp_te->update_nav_model(true);
    mp_pe->update_models(true);
    mp_de->update_models();
    if(mqh_data.contains(FLD_LS_AINDEX))
        mp_te->set_ap_selection(mqh_data.value(FLD_LS_AINDEX));
    if(mqh_data.contains(FLD_LS_TINDEX))
        mp_pe->set_tenant_selected(mqh_data.value(FLD_LS_TINDEX));
    dec_list_sel();
    QWidget::showEvent(ev);
}

void DlgLeaseEdit::select_apartment(QVariant qv_a_index)
{
    if(qv_a_index.isNull())
    {
        mqh_data.remove(FLD_LS_AINDEX);
        update_room_count();
        return;
    }
    mqh_data[FLD_LS_AINDEX] = qv_a_index;
    QString qstr = mp_dbms->get_apartment_info(qv_a_index);
    ui->btn_select_apartment->setText(qstr);
    update_room_count();
    data_changed();
}

void DlgLeaseEdit::select_tenant(QVariant qv_t_index)
{
    if(qv_t_index.isNull()) return;
    mqh_data[FLD_LS_TINDEX] = qv_t_index;
    QString qstr = mp_dbms->get_tenant_fio(qv_t_index,true);
    ui->btn_select_person->setText(qstr);
    data_changed();
}

void DlgLeaseEdit::add_decmaster(QVariant qv_d_index)
{
    qDebug()<<"add dec master: index:"<<qv_d_index;
    if(qv_d_index.isNull()) return;
    if(mqvl_dec_indices.contains(qv_d_index)) return;
    qDebug()<<"adding new dec index";
    mqvl_dec_indices.append(qv_d_index);
    mqvl_dec_dates.append(QVariant(QDate(2000,1,1)));
    mqvl_dec_nums.append(QVariant(QString("1")));
    dec_list_to_form();
    ui->listWidget_decisions->setCurrentRow(mqvl_dec_indices.size()-1);
    data_changed();
}


void DlgLeaseEdit::update_room_count()
{
    ui->list_spaces->clear();
    if(!mqh_data.contains(FLD_LS_AINDEX)) return;

    mqvh_ap_spaces=  mp_dbms->get_data(LAKDB_APARTMENTS, mqh_data.value(FLD_LS_AINDEX)).value(FLD_APDB_LSPSHASH).toHash();
    mqsl_ap_sps_ids = mqvh_ap_spaces.keys();
    for(int i = 0; i<mqsl_ap_sps_ids.size(); i++)
    {
        ui->list_spaces->addItem(mqvh_ap_spaces.value( mqsl_ap_sps_ids.at(i)).toString() + RUSTR(" кв.м."));
    }
    for(int  i = 0; i < ui->list_spaces->count(); i++)
    {
        QListWidgetItem *p_i = ui->list_spaces->item(i);
        p_i->setCheckState(Qt::Unchecked);
    }
    if(!mqh_data.contains(FLD_LS_SPSLST)) return;
    QStringList qsl_s_indices = mqh_data.value(FLD_LS_SPSLST).toStringList();
    foreach(QString qstr_id, qsl_s_indices)
    {
        int index = mqsl_ap_sps_ids.indexOf(qstr_id);
        if(index < 0) continue;
        QListWidgetItem *p_i = ui->list_spaces->item(index);
        p_i->setCheckState(Qt::Checked);
    }
}


QString DlgLeaseEdit::get_dec_list_item_str(int r)
{
    QString qstr;
    qstr = mp_dbms->get_data(LAKDB_DECMASTERS,mqvl_dec_indices.at(r)).value(FLD_DECDB_NAME).toString();
    qstr += RUSTR(" № реш. ");
    qstr += mqvl_dec_nums.at(r).toString();
    qstr += RUSTR(" от ");
    qstr += mqvl_dec_dates.at(r).toDate().toString("dd.MM.yy");
    return qstr;
}

void DlgLeaseEdit::dec_list_to_form()
{
    ui->listWidget_decisions->clear();
    qDebug()<<"dec_list_to_form. dec size"<<mqvl_dec_indices.size();
    for(int i = 0; i< mqvl_dec_indices.size(); i++)
    {
        ui->listWidget_decisions->addItem(get_dec_list_item_str(i));
    }
}


void DlgLeaseEdit::dec_list_sel()
{
    int r = ui->listWidget_decisions->currentRow();
    if(r < 0)
    {
        ui->dedit_dec->setEnabled(false);
        ui->ledit_dec_num->setEnabled(false);
        ui->dedit_dec->hide();
        ui->ledit_dec_num->hide();
        return;
    }
    if(r >= mqvl_dec_indices.size())
    {
        ui->dedit_dec->setEnabled(false);
        ui->ledit_dec_num->setEnabled(false);
        ui->dedit_dec->hide();
        ui->ledit_dec_num->hide();
        return;
    }
    ui->dedit_dec->show();
    ui->ledit_dec_num->show();
    ui->dedit_dec->setEnabled(true);
    ui->dedit_dec->setDate(mqvl_dec_dates.at(r).toDate());

    ui->ledit_dec_num->setEnabled(true);
    ui->ledit_dec_num->setText(mqvl_dec_nums.at(r).toString());
}

void DlgLeaseEdit::update_dec_list_item(int r)
{
    QListWidgetItem *p_item =  ui->listWidget_decisions->item(r);
    p_item->setText(get_dec_list_item_str(r));
}

void DlgLeaseEdit::dec_date_changed()
{
    int r = ui->listWidget_decisions->currentRow();
    if(r < 0) return;
    mqvl_dec_dates[r] = QVariant(ui->dedit_dec->date());
    update_dec_list_item(r);
}

void DlgLeaseEdit::dec_num_changed()
{
    int r = ui->listWidget_decisions->currentRow();
    if(r < 0) return;
    mqvl_dec_nums[r] = ui->ledit_dec_num->text();
    update_dec_list_item(r);
}

void DlgLeaseEdit::del_decmaster()
{
    int r = ui->listWidget_decisions->currentRow();
    if(r < 0) return;
    mqvl_dec_indices.removeAt(r);
    mqvl_dec_dates.removeAt(r);
    mqvl_dec_nums.removeAt(r);
    dec_list_to_form();
    data_changed();
}

void DlgLeaseEdit::accept()
{


    if(!mqh_data.contains(FLD_LS_AINDEX))
    {
        lakhMsgE()<<RUSTR("Ошибка!. Не указано жилое помещение!");
        return;
    }

    //double space = ui->ledit_lease_space->text().toDouble();
    SLEE_HDB_REC qh_ap = mp_dbms->get_data(LAKDB_APARTMENTS, mqh_data.value(FLD_LS_AINDEX));
//    if(space > (qh_ap.value(FLD_APDB_LSPC).toDouble()))
//    {
//        lakhMsg()<<RUSTR("Внимание! Указаная арендуемая площадь больше жилой площади. Площадь скорректирована.");
//        ui->ledit_lease_space->setText(QString::number(qh_ap.value(FLD_APDB_LSPC).toDouble()));
//    }

    if(!mqh_data.contains(FLD_LS_TINDEX))
    {
        lakhMsgE()<<RUSTR("Ошибка!. Не выбран наниматель!");
        return;
    }

    if(ui->ledit_ls_num->text().isEmpty())
    {
        lakhMsgE()<<RUSTR("Ошибка!. Не указан номер договора!");
        return;
    }

    if(ui->combo_lhead->currentText().isEmpty())
    {
        lakhMsgE()<<RUSTR("Ошибка!. Не указана должность отв. лица наймодателя!");
        return;
    }

    if(ui->combo_lfio->currentText().isEmpty())
    {
        lakhMsgE()<<RUSTR("Ошибка!. Не указаны ФИО отв. лица наймодателя!");
        return;
    }
    if(ui->ledit_stopreason->text().isEmpty())
    {
        lakhMsgE()<<RUSTR("Ошибка!. Не указана причина прекращения действия договора!");
        return;
    }
    if(mqvl_dec_indices.isEmpty())
    {
        lakhMsgE()<<RUSTR("Ошибка!. Не указаны органы вынесшие решения  о сдаче жилья в наем!");
        return;
    }

    if(m_num_check)
    {
        QVariant qv_req = ui->ledit_ls_num->text();
        QVariantList qvl_res;
        qvl_res = mp_dbms->get_db(LAKDB_LEASES)->findDataEq(FLD_LS_NUM,qv_req);
        if(qvl_res.size())
        {
            lakhMsgE()<<RUSTR("Ошибка!. В базе уже присутствуют договора с данным номером!");
                return;
        }
    }
   QDialog::accept();
}
